import React, { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from 'react-query';
import {
  BellIcon,
  ShieldCheckIcon,
  GlobeAltIcon,
  PaintBrushIcon,
  Cog6ToothIcon,
} from '@heroicons/react/24/outline';
import api from '../services/api';
import LoadingSpinner from '../components/LoadingSpinner';
import toast from 'react-hot-toast';

const Settings = () => {
  const [activeTab, setActiveTab] = useState('notifications');
  const queryClient = useQueryClient();

  // 获取用户设置
  const { data: settingsData, isLoading } = useQuery(
    'userSettings',
    () => api.get('/users/settings'),
    {
      retry: false,
    }
  );

  // 更新设置
  const updateSettingsMutation = useMutation(
    (data) => api.put('/users/settings', data),
    {
      onSuccess: () => {
        queryClient.invalidateQueries('userSettings');
        toast.success('设置已保存');
      },
      onError: (error) => {
        toast.error(error.response?.data?.error || '保存失败');
      },
    }
  );

  const handleSettingChange = (key, value) => {
    const newSettings = {
      ...settingsData?.data?.settings,
      [key]: value,
    };
    updateSettingsMutation.mutate(newSettings);
  };

  const tabs = [
    { id: 'notifications', name: '通知设置', icon: BellIcon },
    { id: 'privacy', name: '隐私设置', icon: ShieldCheckIcon },
    { id: 'appearance', name: '外观设置', icon: PaintBrushIcon },
    { id: 'general', name: '常规设置', icon: Cog6ToothIcon },
  ];

  if (isLoading) {
    return (
      <div className="flex items-center justify-center h-64">
        <LoadingSpinner size="lg" />
      </div>
    );
  }

  const settings = settingsData?.data?.settings || {};

  return (
    <div className="space-y-6">
      {/* 页面标题 */}
      <div>
        <h1 className="text-2xl font-bold text-gray-900">设置</h1>
        <p className="mt-1 text-sm text-gray-500">
          管理您的应用设置和偏好
        </p>
      </div>

      <div className="grid grid-cols-1 gap-6 lg:grid-cols-4">
        {/* 设置导航 */}
        <div className="lg:col-span-1">
          <nav className="space-y-1">
            {tabs.map((tab) => {
              const Icon = tab.icon;
              return (
                <button
                  key={tab.id}
                  onClick={() => setActiveTab(tab.id)}
                  className={`${
                    activeTab === tab.id
                      ? 'nav-link-active'
                      : 'nav-link-inactive'
                  } group flex items-center px-3 py-2 text-sm font-medium rounded-md w-full`}
                >
                  <Icon className="mr-3 h-5 w-5" />
                  {tab.name}
                </button>
              );
            })}
          </nav>
        </div>

        {/* 设置内容 */}
        <div className="lg:col-span-3">
          <div className="card">
            <div className="card-body">
              {/* 通知设置 */}
              {activeTab === 'notifications' && (
                <div className="space-y-6">
                  <div>
                    <h3 className="text-lg font-medium text-gray-900">通知设置</h3>
                    <p className="mt-1 text-sm text-gray-500">
                      管理您接收的通知类型
                    </p>
                  </div>

                  <div className="space-y-4">
                    <div className="flex items-center justify-between">
                      <div>
                        <h4 className="text-sm font-medium text-gray-900">任务通知</h4>
                        <p className="text-sm text-gray-500">任务分配、状态变更等通知</p>
                      </div>
                      <label className="relative inline-flex items-center cursor-pointer">
                        <input
                          type="checkbox"
                          checked={settings.taskNotifications !== false}
                          onChange={(e) => handleSettingChange('taskNotifications', e.target.checked)}
                          className="sr-only peer"
                        />
                        <div className="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-primary-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-primary-600"></div>
                      </label>
                    </div>

                    <div className="flex items-center justify-between">
                      <div>
                        <h4 className="text-sm font-medium text-gray-900">项目通知</h4>
                        <p className="text-sm text-gray-500">项目更新、成员变更等通知</p>
                      </div>
                      <label className="relative inline-flex items-center cursor-pointer">
                        <input
                          type="checkbox"
                          checked={settings.projectNotifications !== false}
                          onChange={(e) => handleSettingChange('projectNotifications', e.target.checked)}
                          className="sr-only peer"
                        />
                        <div className="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-primary-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-primary-600"></div>
                      </label>
                    </div>

                    <div className="flex items-center justify-between">
                      <div>
                        <h4 className="text-sm font-medium text-gray-900">团队通知</h4>
                        <p className="text-sm text-gray-500">团队邀请、成员变更等通知</p>
                      </div>
                      <label className="relative inline-flex items-center cursor-pointer">
                        <input
                          type="checkbox"
                          checked={settings.teamNotifications !== false}
                          onChange={(e) => handleSettingChange('teamNotifications', e.target.checked)}
                          className="sr-only peer"
                        />
                        <div className="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-primary-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-primary-600"></div>
                      </label>
                    </div>

                    <div className="flex items-center justify-between">
                      <div>
                        <h4 className="text-sm font-medium text-gray-900">邮件通知</h4>
                        <p className="text-sm text-gray-500">通过邮件接收重要通知</p>
                      </div>
                      <label className="relative inline-flex items-center cursor-pointer">
                        <input
                          type="checkbox"
                          checked={settings.emailNotifications !== false}
                          onChange={(e) => handleSettingChange('emailNotifications', e.target.checked)}
                          className="sr-only peer"
                        />
                        <div className="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-primary-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-primary-600"></div>
                      </label>
                    </div>
                  </div>
                </div>
              )}

              {/* 隐私设置 */}
              {activeTab === 'privacy' && (
                <div className="space-y-6">
                  <div>
                    <h3 className="text-lg font-medium text-gray-900">隐私设置</h3>
                    <p className="mt-1 text-sm text-gray-500">
                      管理您的隐私和数据保护设置
                    </p>
                  </div>

                  <div className="space-y-4">
                    <div className="flex items-center justify-between">
                      <div>
                        <h4 className="text-sm font-medium text-gray-900">公开个人资料</h4>
                        <p className="text-sm text-gray-500">允许其他用户查看您的基本信息</p>
                      </div>
                      <label className="relative inline-flex items-center cursor-pointer">
                        <input
                          type="checkbox"
                          checked={settings.publicProfile !== false}
                          onChange={(e) => handleSettingChange('publicProfile', e.target.checked)}
                          className="sr-only peer"
                        />
                        <div className="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-primary-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-primary-600"></div>
                      </label>
                    </div>

                    <div className="flex items-center justify-between">
                      <div>
                        <h4 className="text-sm font-medium text-gray-900">显示在线状态</h4>
                        <p className="text-sm text-gray-500">让其他用户知道您是否在线</p>
                      </div>
                      <label className="relative inline-flex items-center cursor-pointer">
                        <input
                          type="checkbox"
                          checked={settings.showOnlineStatus !== false}
                          onChange={(e) => handleSettingChange('showOnlineStatus', e.target.checked)}
                          className="sr-only peer"
                        />
                        <div className="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-primary-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-primary-600"></div>
                      </label>
                    </div>
                  </div>
                </div>
              )}

              {/* 外观设置 */}
              {activeTab === 'appearance' && (
                <div className="space-y-6">
                  <div>
                    <h3 className="text-lg font-medium text-gray-900">外观设置</h3>
                    <p className="mt-1 text-sm text-gray-500">
                      自定义应用的外观和主题
                    </p>
                  </div>

                  <div className="space-y-4">
                    <div>
                      <label className="block text-sm font-medium text-gray-700">主题</label>
                      <select
                        value={settings.theme || 'light'}
                        onChange={(e) => handleSettingChange('theme', e.target.value)}
                        className="mt-1 input"
                      >
                        <option value="light">浅色主题</option>
                        <option value="dark">深色主题</option>
                        <option value="auto">跟随系统</option>
                      </select>
                    </div>

                    <div>
                      <label className="block text-sm font-medium text-gray-700">语言</label>
                      <select
                        value={settings.language || 'zh-CN'}
                        onChange={(e) => handleSettingChange('language', e.target.value)}
                        className="mt-1 input"
                      >
                        <option value="zh-CN">简体中文</option>
                        <option value="en-US">English</option>
                      </select>
                    </div>
                  </div>
                </div>
              )}

              {/* 常规设置 */}
              {activeTab === 'general' && (
                <div className="space-y-6">
                  <div>
                    <h3 className="text-lg font-medium text-gray-900">常规设置</h3>
                    <p className="mt-1 text-sm text-gray-500">
                      管理应用的基本设置
                    </p>
                  </div>

                  <div className="space-y-4">
                    <div>
                      <label className="block text-sm font-medium text-gray-700">时区</label>
                      <select
                        value={settings.timezone || 'Asia/Shanghai'}
                        onChange={(e) => handleSettingChange('timezone', e.target.value)}
                        className="mt-1 input"
                      >
                        <option value="Asia/Shanghai">北京时间 (UTC+8)</option>
                        <option value="America/New_York">纽约时间 (UTC-5)</option>
                        <option value="Europe/London">伦敦时间 (UTC+0)</option>
                        <option value="Asia/Tokyo">东京时间 (UTC+9)</option>
                      </select>
                    </div>

                    <div>
                      <label className="block text-sm font-medium text-gray-700">日期格式</label>
                      <select
                        value={settings.dateFormat || 'YYYY-MM-DD'}
                        onChange={(e) => handleSettingChange('dateFormat', e.target.value)}
                        className="mt-1 input"
                      >
                        <option value="YYYY-MM-DD">2024-01-15</option>
                        <option value="MM/DD/YYYY">01/15/2024</option>
                        <option value="DD/MM/YYYY">15/01/2024</option>
                      </select>
                    </div>

                    <div>
                      <label className="block text-sm font-medium text-gray-700">时间格式</label>
                      <select
                        value={settings.timeFormat || '24h'}
                        onChange={(e) => handleSettingChange('timeFormat', e.target.value)}
                        className="mt-1 input"
                      >
                        <option value="24h">24小时制 (14:30)</option>
                        <option value="12h">12小时制 (2:30 PM)</option>
                      </select>
                    </div>
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default Settings;
